﻿Imports System.IO
Imports System.Xml.Serialization
Imports SFDL.LoaderExtensions

Module WSSHelper

    Dim WSS As New WebSocketSharp.Server.WebSocketServer
    Private _log As NLog.Logger = NLog.LogManager.GetLogger("RemoteControl")

    ''' <summary>
    ''' Diese Funktion serialisiert ein Objekt und speichert es als XML-Format Datei
    ''' </summary>
    ''' <param name="Obj">Das zu serialisierende Objekt</param>
    Public Function WSSXMLSerialize(ByVal Obj As Object) As String

        Dim XML As New XmlSerializer(Obj.GetType)

        Using textWriter As New StringWriter()
            XML.Serialize(textWriter, Obj)
            Return textWriter.ToString()
        End Using

    End Function

    ''' <summary>
    ''' Diese Funktion deserialisiert eine XML Datei und gibt das Ergebnis in ein Objekt zurück
    ''' </summary>
    ''' <param name="XMLString">Der XML String aus dem gelesen werden soll</param>
    Public Function WSSXMLDeSerialize(ByVal Obj As Object, ByVal XMLString As String) As Object

        Dim XML As New XmlSerializer(Obj.GetType)
        Dim RetObj As Object

        Using _textreader As New StringReader(XMLString)
            RetObj = XML.Deserialize(_textreader)
        End Using

        Return RetObj

    End Function

    Public Sub ProgressRemoteControlState(ByVal _rc_settings As RemoteControlSettings)

        Try

            If _rc_settings.Enabled = False And WSS.IsListening Then
                WSS.Stop()
            End If

            If _rc_settings.Enabled = True And WSS.IsListening = False Then

                WSS = New WebSocketSharp.Server.WebSocketServer(String.Format("ws://{0}:{1}", _rc_settings.IPAdress, _rc_settings.Port))
                WSS.KeepClean = True
                WSS.ReuseAddress = True
                WSS.WaitTime = TimeSpan.FromSeconds(3)
                WSS.SslConfiguration = Nothing 'Kein SSL Cert Check
                WSS.AuthenticationSchemes = WebSocketSharp.Net.AuthenticationSchemes.Basic

                WSS.UserCredentialsFinder = Function(id)

                                                Dim name = id.Name

                                                ' Return user name, password, and roles.
                                                ' If the user credentials aren't found.
                                                Return If(_settings.RemoteControlSettings.APIKeyList.Where(Function(key) key.Equals(name)).Count = 1, New WebSocketSharp.Net.NetworkCredential(name, RandomString(8), "User"), Nothing)

                                            End Function

                WSS.AddWebSocketService(Of WSS_SFDLRemoteControlBase)("/SFDLRemote")

                WSS.Start()

                If WSS.IsListening = True Then
                    _log.Info("WebSocket RemoteControl Server erfolgreich gestartet!")
                Else
                    _log.Warn("WebSocket RemoteControl Server wurde nicht gestartet!")
                End If

            End If

        Catch ex As Exception
            _log.Error(ex, ex.Message)
        End Try


    End Sub

End Module
